<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryinfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="180">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUserBtn(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 分配按钮 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="setUserRole(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[2, 5, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <span>
        <el-form
          :model="userInfo"
          :rules="addUserRules"
          ref="addUserFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInfo.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="userInfo.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="userInfo.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        :model="editUser"
        :rules="editUserRules"
        ref="editUserFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 为用户分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <div>
        <p>当前用户：{{ userinfos.username }}</p>
        <p>当前角色：{{ userinfos.role_name }}</p>
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSetRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "myUser",
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value))
        //合法的邮箱
        return cb();
      cb(new Error("请输入合法的邮箱"));
    };
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[3|4|5|7|8|9][0-9]\d{8}$/;
      if (regMobile.test(value))
        //合法的手机号
        cb();
      cb(new Error("请输入合法的手机号"));
    };
    return {
      userList: [], //用户列表
      total: 0,
      addDialogVisible: false, //添加用户对话框
      editDialogVisible: false, //编辑用户对话框,
      setRightDialogVisible: false, //分配角色对话框
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userInfo: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editUser: {},
      //添加用户的表单 验证规则
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "用户名长度在3到15之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "密码长度在6到15之间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //编辑用户的表单 验证规则
      editUserRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      rolesList: [], //角色列表
      //需要被分配角色的用户信息
      userinfos: {},
      selectedRoleId: "", //已选中的角色id值
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryinfo,
      });
      // console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败");
      (this.userList = res.data.users), (this.total = res.data.total);
    },
    //监听pagesize的改变
    handleSizeChange(pagesize) {
      // console.log(pagesize);
      this.queryinfo.pagesize = pagesize;
      this.getUserList();
    },
    handleCurrentChange(pagenum) {
      // console.log(pagenum);
      this.queryinfo.pagenum = pagenum;
      this.getUserList();
    },
    //用户状态的改变
    async userStateChange(user) {
      console.log(user);
      const { data: res } = await this.$http.put(
        `users/${user.id}/state/${user.mg_state}`
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state;
        return this.$message.error("修改用户状态失败！");
      }
      this.$message.success("更新用户状态成功！");
    },
    //监听对话框的关闭事件
    addDialogClose() {
      this.$refs.addUserFormRef.resetFields();
    },
    //点击按钮，添加用户
    addUser() {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.userInfo);
        if (res.meta.status !== 201)
          return this.$message.error("添加用户失败！");
        this.$message.success("添加用户成功！");
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    //点击编辑按钮
    async editUserBtn(id) {
      this.editDialogVisible = true;
      //根据id查询用户
      const { data: res } = await this.$http.get("users/" + id);
      if (res.meta.status !== 200)
        return this.$message.error("获取该用户信息失败！");
      this.editUser = res.data;
      // console.log(this.editUser);
    },
    //编辑按钮确定编辑用户
    editUserInfo() {
      this.$refs.editUserFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "users/" + this.editUser.id,
          {
            email: this.editUser.email,
            mobile: this.editUser.mobile,
          }
        );
        if (res.meta.status !== 200) return this.$message.error("更新失败！");
        this.$message.success(res.meta.msg);
        this.editDialogVisible = false;
        this.getUserList();
      });
    },
    //编辑对话框的关闭事件
    editDialogClose() {
      this.$refs.editUserFormRef.resetFields();
    },
    //根据id删除用户
    async deleteUser(id) {
      const result = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (result === "confirm") {
        const { data: res } = await this.$http.delete("users/" + id);
        if (res.meta.status !== 200)
          return this.$message.error("删除用户失败！");
        this.$message.success("删除用户成功！");
        this.getUserList();
      }
    },
    // 点击分配角色，显示分配角色对话框
    async setUserRole(role) {
      this.userinfos = role;
      //获取所有角色
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败！");
      this.rolesList = res.data;
      this.setRightDialogVisible = true;
    },
    //点击分配角色对话框的确定按钮
    async saveSetRole() {
      if (!this.selectedRoleId) return this.$message.error("请选择角色！");
      //更新用户的角色
      const { data: res } = await this.$http.put(
        `users/${this.userinfos.id}/role`,
        { rid: this.selectedRoleId }
      );
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("更新角色失败！");
      this.$message.success("更新角色成功");
      this.getUserList();
      this.setRightDialogVisible = false;
    },
    //分配角色对话框的关闭事件
    setRightDialogClose() {
      this.selectedRoleId = "";
      this.userinfos = {};
    },
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 14px;
  font-size: 12px;
}
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>